<template>
  <view class="community-container">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <input type="text" v-model="searchText" placeholder="搜索话题..." />
      <button class="publish-btn" @click="navigateToPublish">发布</button>
    </view>

    <!-- 标签导航 -->
    <scroll-view class="tags-scroll" scroll-x>
      <view class="tags-container">
        <view 
          v-for="(tag, index) in allTags" 
          :key="index"
          :class="['tag-item', currentTag === tag ? 'active' : '']"
          @click="selectTag(tag)"
        >
          {{ tag }}
        </view>
      </view>
    </scroll-view>

    <!-- 帖子列表 -->
    <scroll-view class="posts-list" scroll-y>
      <view class="post-item" v-for="(post, index) in filteredPosts" :key="index" @click="goToDetail(index)">
        <view class="post-header">
          <image class="avatar" :src="post.user.avatar || 'https://img1.baidu.com/it/u=4113779165,197494311&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800'" mode="aspectFill"></image>
          <view class="post-info">
            <text class="username">{{ post.user.username }}</text>
            <text class="time">{{ post.created_at }}</text>
          </view>
        </view>
        <view class="post-content">
          <text class="post-text">
            <template v-for="(part, idx) in parseContent(post.content)" :key="idx">
              <text v-if="part.isTopic" class="topic-blue">{{ part.text }}</text>
              <text v-else>{{ part.text }}</text>
            </template>
          </text>
          <view class="post-images" v-if="post.images && post.images.length">
            <image 
              v-for="(img, imgIndex) in post.images" 
              :key="imgIndex"
              :src="img"
              mode="aspectFill"
              @click="previewImage(post.images, imgIndex)"
            ></image>
          </view>
        </view>
        <view class="post-footer">
          <view class="action-btn" @click="likePost(index)">
            <uni-icons type="heart" size="20" :color="post.is_liked ? '#ff4d4f' : '#666'"></uni-icons>
            <text>{{ post.likes_count }}</text>
          </view>
          <view class="action-btn" @click="showComments(index)">
            <uni-icons type="chat" size="20" color="#666"></uni-icons>
            <text>{{ post.comments_count }}</text>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { request } from '@/utiles/request'

export default {
  data() {
    return {
      searchText: '',
      currentTag: '全部',
      allTags: ['全部'],
      posts: [],
      page: 1,
      pageSize: 10,
      hasMore: true,
      loading: false,
      user_id: 1 // 这里应该从用户状态或缓存中获取
    }
  },
  computed: {
    filteredPosts() {
      let posts = this.posts;
      // 标签筛选
      if (this.currentTag !== '全部') {
        posts = posts.filter(post => post.content.includes(this.currentTag));
      }
      // 关键字搜索
      if (this.searchText.trim()) {
        const keyword = this.searchText.trim().toLowerCase();
        posts = posts.filter(post => post.content.toLowerCase().includes(keyword));
      }
      return posts;
    }
  },
  onLoad() {
    this.loadPosts()
  },
  onPullDownRefresh() {
    this.page = 1
    this.posts = []
    this.hasMore = true
    this.loadPosts().then(() => {
      uni.stopPullDownRefresh()
    })
  },
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.page++
      this.loadPosts()
    }
  },
  methods: {
    async loadPosts() {
      if (this.loading) return
      this.loading = true
      
      try {
        const res = await request({
          url: '/admin/api/community/posts',
          method: 'GET',
          data: {
            page: this.page,
            pageSize: this.pageSize,
            tag: this.currentTag === '全部' ? '' : this.currentTag
          }
        })
        console.log(res)
        if (res.data.code === 200) {
          const { list, total } = res.data.data
          this.posts = this.page === 1 ? list : [...this.posts, ...list]
          this.hasMore = this.posts.length < total
          this.extractAllTags();
        } else {
          uni.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    extractAllTags() {
      const tagSet = new Set();
      this.posts.forEach(post => {
        const regex = /#([^#\s,.，。！？!?]+)/g;
        let match;
        while ((match = regex.exec(post.content)) !== null) {
          tagSet.add(match[0]);
        }
      });
      this.allTags = ['全部', ...Array.from(tagSet)];
    },
    selectTag(tag) {
      this.currentTag = tag
      this.page = 1
      this.posts = []
      this.hasMore = true
      this.loadPosts()
    },
    navigateToPublish() {
      uni.navigateTo({
        url: '/pages/communityPublish/communityPublish'
      })
    },
    async likePost(index) {
      const post = this.posts[index]
      try {
        const res = await request({
          url: `/admin/api/community/posts/${post.id}/like`,
          method: 'POST',
          data: {
            user_id: this.user_id
          }
        })
        
        if (res.data.code === 200) {
          const { likes_count, is_liked } = res.data.data
          this.posts[index].likes_count = likes_count
          this.posts[index].is_liked = is_liked
        } else {
          uni.showToast({
            title: res.data.message || '操作失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    },
    showComments(index) {
      const post = this.posts[index]
      uni.navigateTo({
        url: `/pages/communityDetail/communityDetail?id=${post.id}`
      })
    },
    previewImage(images, current) {
      uni.previewImage({
        urls: images,
        current: images[current]
      })
    },
    goToDetail(index) {
      const post = this.posts[index]
      uni.navigateTo({
        url: `/pages/communityDetail/communityDetail?id=${post.id}`
      })
    },
    parseContent(content) {
      const regex = /#([^#\s,.，。！？!?]+)/g;
      let result = [];
      let lastIndex = 0;
      let match;
      while ((match = regex.exec(content)) !== null) {
        if (match.index > lastIndex) {
          result.push({ text: content.slice(lastIndex, match.index), isTopic: false });
        }
        result.push({ text: match[0], isTopic: true });
        lastIndex = regex.lastIndex;
      }
      if (lastIndex < content.length) {
        result.push({ text: content.slice(lastIndex), isTopic: false });
      }
      return result;
    }
  }
}
</script>

<style>
.community-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.search-bar {
  padding: 20rpx;
  display: flex;
  background-color: #ffffff;
  position: sticky;
  top: 0;
  z-index: 100;
}

.search-bar input {
  flex: 1;
  height: 70rpx;
  background-color: #f5f7fa;
  border-radius: 35rpx;
  padding: 0 30rpx;
  margin-right: 20rpx;
}

.publish-btn {
  width: 140rpx;
  height: 70rpx;
  line-height: 70rpx;
  background-color: #4CAF50;
  color: #ffffff;
  border-radius: 35rpx;
  font-size: 28rpx;
}

.tags-scroll {
  background-color: #ffffff;
  padding: 20rpx 0;
  white-space: nowrap;
}

.tags-container {
  display: inline-flex;
  padding: 0 20rpx;
}

.tag-item {
  padding: 10rpx 30rpx;
  margin-right: 20rpx;
  background-color: #f5f7fa;
  border-radius: 30rpx;
  font-size: 28rpx;
  color: #666;
}

.tag-item.active {
  background-color: #4CAF50;
  color: #ffffff;
}

.posts-list {
  width: 95%;
  padding: 20rpx;
}

.post-item {
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.post-info {
  flex: 1;
}

.username {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-right: 20rpx;
}

.time {
  font-size: 24rpx;
  color: #999;
  margin-left: 10rpx;
  margin-top: 6rpx;
}

.post-content {
  margin-bottom: 20rpx;
}

.post-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
}

.post-images {
  display: flex;
  flex-wrap: wrap;
  margin-top: 20rpx;
}

.post-images image {
  width: 220rpx;
  height: 220rpx;
  margin-right: 10rpx;
  margin-bottom: 10rpx;
  border-radius: 10rpx;
}

.post-footer {
  display: flex;
  border-top: 1rpx solid #eee;
  padding-top: 20rpx;
}

.action-btn {
  display: flex;
  align-items: center;
  margin-right: 40rpx;
  color: #666;
}

.action-btn text {
  font-size: 26rpx;
  margin-left: 10rpx;
}

.topic-blue {
  color: #1890ff;
}
</style>